﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLBH.ConfigLib;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;
namespace Module.SystemUI
{
    public partial class FrmBackUp_RestoreDatabase : Form
    {
        QLBHSettings settings;
        public string FileRestore
        {
            get { return txtFileName.Text; }
        }
        public string UserName
        {
            get{
                if (settings!=null)
                {
                    return settings.UserName;
                }else
                {
                    return string.Empty;
                }
            }
           
        }
        public string PassWord
        {
            get
            {
                if (settings != null)
                {
                    return settings.PassWord;
                }
                else
                {
                    return string.Empty;
                }
            }
           
        }
        public string ServerName
        {
            get
            {
                if (settings != null)
                {
                    return settings.ServerName;
                }
                else
                {
                    return string.Empty;
                }
            }
            
        }
        public string FileName
        {
            get { return Path.Combine(txtFolde.Text, txtFile.Text); }
            
        }
        public string DatabaseName{
            get { return "QLBH"; }
        }
        public FrmBackUp_RestoreDatabase()
        {
            InitializeComponent();
        }

       

        private void FrmBackUp_RestoreDatabase_Load(object sender, EventArgs e)
        {
            btnSaoLuu.Enabled = false;
            btnphuchoi.Enabled = false;
            txtFile.Text = DatabaseName + DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss")+".bak";
            if (settings==null)
            {
                settings = QLBHSettings.Instance;
            }
        }

        private void txtFolde_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void btnFolde_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dia = new FolderBrowserDialog();
            if (dia.ShowDialog() == DialogResult.OK)
            {
                txtFolde.Text = dia.SelectedPath;
                if (string.IsNullOrWhiteSpace(txtFolde.Text) || txtFolde.Text.StartsWith("C:"))
                {
                    btnSaoLuu.Enabled = false;
                    MessageBox.Show("Bạn Chưa Chọn Thư mục Lưu trữ hoặc bạn chon thư mục chứa chương trinh của hệ thống", "cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtFolde.Text = string.Empty;
                    return;

                }
                else
                {
                    btnSaoLuu.Enabled = true;
                }
            }
        }
        private void RestoreDatabase(string databaseName,string serverName,string userName,string passWord,string fileName)
        {
            try
            {
                Restore sqlRestore = new Restore();

                BackupDeviceItem deviceItem = new BackupDeviceItem(fileName, DeviceType.File);
                sqlRestore.Devices.Add(deviceItem);
                sqlRestore.Database = databaseName;

                ServerConnection connection = new ServerConnection(serverName, userName, passWord);
                

                Server sqlServer = new Server(connection);

                Database db = sqlServer.Databases[databaseName];
                if (db != null)
                {
                    sqlServer.KillAllProcesses(db.Name);
                    db.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;
                    db.Alter(TerminationClause.RollbackTransactionsImmediately);
                }
                sqlRestore.Action = RestoreActionType.Database;

                db = sqlServer.Databases[databaseName];


                sqlRestore.SqlRestore(sqlServer);
                connection.Connect();
                if (connection.IsOpen)
                {
                    SqlConnection sqlConnection = connection.SqlConnectionObject;
                    SqlCommand sqlCommand = new SqlCommand();
                    sqlCommand.Connection = sqlConnection;
                    sqlCommand.CommandType = CommandType.Text;
                    sqlCommand.CommandText = "ALTER DATABASE"+" " + databaseName + " SET MULTI_USER WITH NO_WAIT";
                    sqlCommand.ExecuteNonQuery();
                }
               
                db = sqlServer.Databases[databaseName];


                db.Refresh();

                sqlServer.Refresh();
            }
            catch (System.Exception ex)
            {
            	throw ex;
            }
        }
        private void BackupDatabase(string databaseName,string serverName,string userName,string passWord,string fileName)
        {
            Backup sqlBackup = new Backup();

            sqlBackup.Action = BackupActionType.Database;
            sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
                                             DateTime.Now.ToShortDateString();
            sqlBackup.BackupSetName = "Archive";

            sqlBackup.Database = databaseName;

            BackupDeviceItem deviceItem = new BackupDeviceItem(fileName, DeviceType.File);
            ServerConnection connection = new ServerConnection(serverName, userName, passWord);
            try
            {
                connection.Connect();
                if (connection.IsOpen)
                {
                    Server sqlServer = new Server(connection);

                    Database db = sqlServer.Databases[databaseName];
                    if (db != null)
                    {
                        sqlServer.KillAllProcesses(db.Name);
                        db.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;
                        db.Alter(TerminationClause.RollbackTransactionsImmediately);
                    }
                    sqlBackup.Initialize = true;
                    sqlBackup.Checksum = true;
                    sqlBackup.ContinueAfterError = true;

                    sqlBackup.Devices.Add(deviceItem);
                    sqlBackup.Incremental = false;

                   

                    sqlBackup.FormatMedia = false;

                    sqlBackup.SqlBackup(sqlServer);
                    Database dbs = sqlServer.Databases[databaseName];
                    dbs.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple;
                    dbs.SetOnline();
                }
                else
                {
                    throw new Exception("Khong the ket noi den database");
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
           
        }

        private void btnSaoLuu_Click(object sender, EventArgs e)
        {
            try
            {
                BackupDatabase(DatabaseName, ServerName, UserName, PassWord, FileName);
                MessageBox.Show("Thành công");
                this.DialogResult = DialogResult.OK;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
           
        }

        private void btnChooseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "File(*.bak)|*.bak";
            if (file.ShowDialog()==DialogResult.OK)
            {
                txtFileName.Text = file.FileName;
                if (string.IsNullOrWhiteSpace(txtFileName.Text))
                {
                    btnphuchoi.Enabled = false;
                }
                else
                    btnphuchoi.Enabled = true;
            }
        }

        private void btnphuchoi_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dia = MessageBox.Show("bạn sẽ mất dữ liệu hiện hành nếu phục hồi xong.Bạn có muốn tiếp tục không?", "Thông Báo",MessageBoxButtons.YesNo,MessageBoxIcon.Question );
                if (dia==DialogResult.Yes)
                {
                    RestoreDatabase(DatabaseName, ServerName, UserName, PassWord, FileRestore);
                    MessageBox.Show("thành công");
                    this.DialogResult = DialogResult.OK;
                }
                
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
